package com.atguigu.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

/*************************************************
                时间: 2021-05-13
                作者: 刘  辉
                描述: 
  ************************************************/
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/hello")
    public String success(int i){
        int result = 10/i;
        int[] nums=new int[]{1,2,5};
        System.out.println("hello world......"+nums[i]);
        return "success";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> downloadFile(HttpServletRequest request) throws IOException {
        String fileName="风吹麦浪.mp3";
        String realPath = request.getServletContext().getRealPath("/WEB-INF/" + fileName);
        FileInputStream fis = new FileInputStream(realPath);

        byte[] body=new byte[fis.available()];
        fis.read(body);
        MultiValueMap<String,String> headers= new HttpHeaders();//设置响应头信息
        //解决文件名乱码问题
        fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
        //不再被浏览器解析，会被当做附件下载
        headers.add("Content-Disposition", "attachment;filename="+fileName);

        HttpStatus httpStatus =HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(body,headers,httpStatus);
        return entity;
    }

    @RequestMapping("/upload")
    public ModelAndView uploadFile(String username, HttpServletRequest request, MultipartFile photo) throws IOException {
       // String name = photo.getName(); //获取表单项的name值
       String fileName = UUID.randomUUID().toString()+photo.getOriginalFilename();//获取上传文件的名字
        String realPath = request.getServletContext().getRealPath("/upload");
        File file = new File(realPath);
        //当该文件夹不存在的时候，就创建出来
        if(!file.exists()){
            file.mkdirs();
        }
        //文件上传|下载：将输入流转换为输出流
        InputStream inputStream = photo.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + fileName);
     //photo.transferTo(new File(realPath + "/" + fileName));
        IOUtils.copy(inputStream,fileOutputStream);
        fileOutputStream.flush();//刷新内存中的内容到磁盘
        //关闭输出、输入流
        fileOutputStream.close();
        inputStream.close();
        ModelAndView mv = new ModelAndView( "success");
        mv.addObject("photo",fileName);
        return mv;
    }
}
